package com.google.jacli.compiler;

import java.lang.reflect.Field;
import java.util.List;
import com.google.jacli.Argument;

public class SequenceCompiler extends AbstractCompiler {

    @SuppressWarnings("unchecked")
    public void compile(final List<Field> fieldList, final Object target, final String[] args) {
        Field lastField = null;
        for (Field field : fieldList) {
            lastField = field;
            Argument argument = getArgument(field);
                
            if (argument.id() <= args.length - 1) {
                setValue(field, target, args[argument.id()]);
            } else if (argument.required()) {
                if (argument.defaultValue().length() == 0) {
                    this.command.getExceptions().add(new IllegalArgumentException("The required argument at position #"
                                                                                  + argument.id()
                                                                                  + " is missing"));
                }
                setValue(field, target, argument.defaultValue());
                continue;
            }
        }
            
        if (args.length > fieldList.size() && lastField.getType() == List.class) {
            try {
                List<String> f = (List<String>)lastField.get(target);
                for (int i = fieldList.size(); i < args.length; i++) {
                    f.add(args[i]);
                }
            } catch (IllegalAccessException e) {
                this.command.getExceptions().add(e);
            }
        }
    }
}